package com.example.group.network.express_plus_app;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.group.network.express_plus_app.bean.MyResponse;
import com.example.group.network.express_plus_app.http.MySingleton;
import com.xuexiang.xui.XUI;

import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class AddMyOrderActivity extends AppCompatActivity implements View.OnClickListener,
        AdapterView.OnItemSelectedListener, DatePickerDialog.OnDateSetListener , TimePickerDialog.OnTimeSetListener {
    RequestQueue queue;
    EditText et_estimated_price;
    EditText et_add_delivery_address;
    EditText et_user_leisure;
    EditText et_delivery_mode;
    EditText et_express_detail_address;
    EditText et_stuff_detail;
    TextView et_user_leisure_time;
    Spinner sp_express_type;
    String phone;
    String token;
    String server_ip;
    HashMap<String, String> mInfoMap=MainApplication.getInstance().mInfoMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_my_order);
        XUI.initTheme(this);
        server_ip= getApplication().getString(R.string.server_ip);
        setActionBar("发布待取件信息");
        initParam();

    }


    private String[] stuffType={"食品","生活用品","家电","服饰","数码","百货","生鲜"};
    public void initParam(){
        queue= MySingleton.getInstance(getApplicationContext()).getRequestQueue();
        findViewById(R.id.btn_post_order).setOnClickListener(this);
        et_estimated_price=findViewById(R.id.et_estimated_price);
        et_add_delivery_address=findViewById(R.id.et_add_delivery_address);
        et_add_delivery_address.setText(mInfoMap.get("delivery_address"));
        et_user_leisure=findViewById(R.id.et_user_leisure);
        et_user_leisure.setOnClickListener(this);
        et_user_leisure_time=findViewById(R.id.et_user_leisure_time);
        et_user_leisure_time.setOnClickListener(this);
        et_delivery_mode=findViewById(R.id.et_delivery_mode);
        et_express_detail_address=findViewById(R.id.et_express_detail_address);
        et_stuff_detail=findViewById(R.id.et_stuff_detail);
        sp_express_type=findViewById(R.id.sp_express_type);
        ArrayAdapter<String> typeAdapter=new ArrayAdapter<String>(this,R.layout.item_select,stuffType);
        typeAdapter.setDropDownViewResource(R.layout.item_dropdown);

        sp_express_type = (Spinner) findViewById(R.id.sp_express_type);
        sp_express_type.setPrompt("请选择您的快递类型");
        sp_express_type.setAdapter(typeAdapter);
        sp_express_type.setSelection(0);
        sp_express_type.setOnItemSelectedListener(this);
        HashMap<String, String> mInfoMap = MainApplication.getInstance().mInfoMap;
        phone=mInfoMap.get("phone");
        token=mInfoMap.get("token");


    }



    public void setActionBar(String title){
        //标题栏设置
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_ios_24);
        supportActionBar.setTitle(title);

    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //按钮监听
    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.btn_post_order){
            postOrder();
        }else if (v.getId()==R.id.et_user_leisure){
            Calendar calendar = Calendar.getInstance();
            DatePickerDialog dialog = new DatePickerDialog(this, this,
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            dialog.show();
        }else if (v.getId()==R.id.et_user_leisure_time){
            Calendar calendar = Calendar.getInstance();
            TimePickerDialog dialog = new TimePickerDialog(this, this,
                    calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
            dialog.show();
        }


    }

    //下拉选择框监听器
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        sp_express_type.setSelection(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public void postOrder(){
        String estimated_price = et_estimated_price.getText().toString();
        String add_delivery_address = et_add_delivery_address.getText().toString();
        String user_leisure = et_user_leisure.getText().toString()+" "+et_user_leisure_time.getText().toString();
        String delivery_mode = et_delivery_mode.getText().toString();
        String express_detail_address = et_express_detail_address.getText().toString();
        String stuff_detail = et_stuff_detail.getText().toString();
        String express_type = sp_express_type.getSelectedItem().toString();
        String post_order_url=server_ip+"express-order/order/add-order?userPhone="
                +phone+"&expressDetailAddress="+express_detail_address+"&deliveryAddress="+add_delivery_address+"&deliveryMode="+delivery_mode
                +"&expressType="+express_type+"&estimatedPrice="+estimated_price+"&userLeisure="+user_leisure
                +"&stuffDetail="+stuff_detail;

        Log.i("post_order_url",post_order_url);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.POST, post_order_url, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        MyResponse myResponse = JSON.parseObject(response.toString(), MyResponse.class);

                        if (myResponse.getOk()){
                            //更新下数据库用户常用地址
                            showToast("待取件发布成功！");
                        }else {
                            showToast("请检查输入内容！");
                        }
                        //tv_volley_data.setText(tv_volley_data.getText()+",Response: " + response.toString());
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error
                        showToast("请检查网络，连接超时");
                        //tv_volley_data.setText("Response: 连接超时" + error.getNetworkTimeMs());
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> head=new HashMap<>();
                head.put("Authorization","Bearer "+token);
                return head;
            }
        };

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(6000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(jsonObjectRequest);
    }
    private void showToast(String desc) {
        Toast.makeText(getApplicationContext(), desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String desc = String.format("%d年%d月%d日",
                year, month+1, dayOfMonth);
        et_user_leisure.setText(desc);
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String desc = String.format("%d时", hourOfDay);
        et_user_leisure_time.setText(desc);
    }
}